#!/usr/bin/env bash

set -eu
set -o pipefail

#安装目录
ENV="test"
INSTALL_HOME=/opt
#数据存放目录,  ipfs  use data_dir , wuji use /mnt/d
DATA_DIR=/data_dir/xwcNodeData
if id -u wuji >/dev/null 2>&1; then
  DATA_DIR=/mnt/d/xwcNodeData
fi
#程序目录
INSTALL_DIR=${INSTALL_HOME}/xwcNode
SOURCE_ID="1aPTjtyadG6e8vKfePeRSuN1yNfyJ716ukrVtsQ41PGDQPhth7"
SOURCE_IP="36.138.1.13"
PORT=23000

#停止旧的服务
stopService() {
  systemctl stop gather
  systemctl stop node
}

#下载
download() {
  zipFile=$1
  zipPath=$2
  zipUrl="http://natb.nextstorage.cn/pkg/${zipFile}"
  rm -f $zipPath
  wget --header="Host: upgrade.nextstorage.cn" ${zipUrl} -O ${zipPath}

  if [ ! -f "${zipPath}" ]; then
    echo "安装包下载失败:${zipUrl}"
    exit 1
  fi
}

#创建证书
createIdentify() {
  identityBin="${INSTALL_DIR}/identity"
  if [ ! -f "${identityBin}" ]; then
    echo "identity 程序不存在"
    exit 1
  fi
  cmd="${identityBin} create identity --concurrency 1  --difficulty 8 --identity-dir ${DATA_DIR}"
  echo "${cmd}"
  $cmd
}

#节点配置setup
nodeSetup() {
  SERVER_PORT=$PORT
  PRIVATE_PORT=$(expr $PORT + 1)
  CONSOLE_PORT=$(expr $PORT + 2)
  DEBUG_PORT=$(expr $PORT + 9)
  P2P_PORT=$(expr $PORT + 3)

  nodeBin="${INSTALL_DIR}/node"
  if [ ! -f "${nodeBin}" ]; then
    echo "node 程序不存在"
    exit 1
  fi
  cmd="${nodeBin} setup --config-dir ${DATA_DIR} --identity-dir ${DATA_DIR}/identity \
	--server.address 0.0.0.0:${SERVER_PORT} --server.private-address 0.0.0.0:${PRIVATE_PORT} \
	--console.address 0.0.0.0:${CONSOLE_PORT} --debug.addr 0.0.0.0:${DEBUG_PORT}  \
	 --operator.wallet 0x0123456789012345678901234567890123456789 \
	 --operator.email storage1@mail.test \
	 --storage2.trust.sources ${SOURCE_ID}@${SOURCE_IP}:10000 \
	 --tracing.app storagenodea/0 \
	--log.output ${DATA_DIR}/storage.log"
  echo -e "\n${cmd}\n"
  $cmd
  echo "配置文件 " ${DATA_DIR}/config.yaml
}

initNode() {
  #下载的包解压到程序目录
  zipFilePath=${1}
  rm -rf ${INSTALL_DIR}
  unzip -o ${zipFilePath} -d ${INSTALL_DIR}

  cd $INSTALL_DIR
  echo $PORT >./.port
  chmod +x gather
  chmod +x identity
  chmod +x node
  #旧的安装目录清理
  rm -rf $DATA_DIR
  mkdir -p $DATA_DIR
  #创建证书
  createIdentify
  #node setup
  nodeSetup
}

updateServiceFile() {
  cd $INSTALL_DIR
  consolePort=$(expr $PORT + 2)
  echo "CONSOLEPORT " $consolePort
  ServerName="${1}.service"
  sed -i "s#HOME#${INSTALL_DIR}#g" ${ServerName}
  sed -i "s#CONSOLEPORT#${consolePort}#g" ${ServerName}
  sed -i "s#CONFIGDIR#${DATA_DIR}#g" ${ServerName}
  sed -i "s#ENV#${ENV}#g" ${ServerName}
  cd -
}

installService() {
  # 安装服务
  cd $INSTALL_DIR
  echo "install " $1
  ServerName=${1}.service
  updateServiceFile "${1}"
  rm -f /etc/systemd/system/${ServerName}
  ln -s ${INSTALL_DIR}/${ServerName} /etc/systemd/system/${ServerName}
  systemctl daemon-reload
  systemctl enable $1
}

startService() {
  systemctl start node
  systemctl start gather
}

createUpdateCrontab() {
  script=${INSTALL_DIR}/update.py
  pyt=`which python3`
  [ "${pyt}" == "" ] && pyt=`which python`
  crontab -l > /tmp/crontmp
  cmd="${pyt} ${script} ${ENV} >${INSTALL_DIR}/update.log 2>&1"
  cmd="flock -xn ${INSTALL_DIR}/update.lock -c \"${cmd}\""
  #删除之前的
  sed -i "/update\.py/d" /tmp/crontmp
  found=`grep -c "${cmd}" /tmp/crontmp`
  if [ $found -eq 0 ];then
      echo "*/60 * * * * ${cmd}" >> /tmp/crontmp
      crontab /tmp/crontmp
      echo "已创建定时任务"
  fi
}

#移除check service
_removeCheckService() {
  systemctl stop check
  rm -f /etc/systemd/system/check.service
  rm -f ${INSTALL_DIR}/check.service
}

#安装
install() {
  # 获取安装版本号
  if [ $# -lt 1 ]; then
    echo "ERROR :  请选择安装包 "
    exit 1
  fi
  echo "开始安装[${1}]"
  #停止旧服务
  set +e
  stopService
  set -e
  zipFilePath="/tmp/${1}"
  #下载安装包
  download ${1} ${zipFilePath}
  #初始化node
  initNode ${zipFilePath}
  #安装服务
  installService "node"
  installService "gather"
  echo "install ok"
  #启动服务
  startService
  #创建crond
  set +e
  createUpdateCrontab
  set -e
  echo "start node ok"
}

#更新
update() {
  # 获取安装版本号
  if [ $# -lt 1 ]; then
    echo "ERROR :  请选择安装包更新 "
    exit 1
  fi
  echo "开始更新[${1}] $@"
  zipFile=${1}
  needUpdate=${@:2}
  #下载安装包
  zipFilePath="/tmp/${zipFile}"
  download ${zipFile} ${zipFilePath}
  set +e
  #停止旧服务
  stopService
  set -e
  #覆盖程序
  echo "unzip -o ${zipFilePath} -d ${INSTALL_DIR} ${needUpdate}"
  unzip -o ${zipFilePath} -d ${INSTALL_DIR} ${needUpdate}
  updateServiceFile "node"
  updateServiceFile "gather"
  #移除check service
  set +e
  _removeCheckService
  createUpdateCrontab
  systemctl daemon-reload
  if [ $? != 0 ]; then
    echo "更新失败"
  fi
  set -e
  #启动服务
  startService
  echo "update node ok"
}

help() {
  echo "use age: "
  echo "${0} <update|install>  <zipName> [可选的需要更新的文件名，update命令支持] [-e test 环境]"
  echo ""
}


main() {

  [ $# == 0 ] && help && exit

  #解析参数
  set -- $(getopt -o e: --long env: -n ${0} -u -- "$@")
  while true; do
    case "${1}" in
    -e | --env)
      ENV="${2}"
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      echo "${1} is not option"
      ;;
    esac
    shift
  done

  #默认是update指令
  if [ "${1}" != "update" ] && [ "${1}" != "install" ]; then
    cmd='update'
  else
    cmd=${1} && shift
  fi

  #生产环境
  if [ "${ENV}" == "prod" ]; then
    SOURCE_ID="12ZDNT2QsqDBTVtfapdpH5YJdA34kK8SsmgQxm5U7fBkGvnCUSP"
    SOURCE_IP="stapi.nextstorage.cn"
  elif [ "${ENV}" == "dev" ]; then
    SOURCE_ID="12g5P8muWTXLEKH1wfGSYnAocU5Xz7jiH6cK4qgJViJvsoTmf1G"
    SOURCE_IP="36.138.1.24"
  fi

  echo "ENV: ${ENV}"
  echo "SOURCE_ID: ${SOURCE_ID}"
  echo "SOURCE_IP: ${SOURCE_IP}"

  $cmd $@
}

main $@



